import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { first } from 'rxjs/operators';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

import { AuthService } from '../../../core/services';

@Component({
  selector: 'kbt-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {

  public validateForm: FormGroup;

  constructor(private fb: FormBuilder, private auth: AuthService, private router: Router) {
  }

  submitForm(): void {
    // const keys = Object.keys(this.validateForm.controls);
    // for (const i of keys) {
    //   this.validateForm.controls[ i ].markAsDirty();
    //   this.validateForm.controls[ i ].updateValueAndValidity();
    // }

    const username = this.validateForm.controls['userName'].value;
    const password = this.validateForm.controls['password'].value;

    if (!username || !password) {
      return;
    }

    this.auth.login(username, password)
    .pipe(first())
    .subscribe(
      result => {
        // 在登录成功后
        // 1.获取当前权限并存入缓存以刷新路由
        this.auth.getRole();
        // 2.跳转路由至首页
        this.router.navigate(['dashboard']);
        // 3.记录当前的登录状态至后台


      },
      error => {
        console.log(error);
      }
    );
  }

  ngOnInit(): void {
    this.validateForm = this.fb.group({
      userName: [ null, [ Validators.required ] ],
      password: [ null, [ Validators.required ] ],
      remember: [ true ]
    });
  }

}
